import { useMemo, useState, forwardRef } from 'react';
import { Tag } from 'antd';
import TableElement, { type TableElementProps, type TableElementRef } from '../TableElement';
import CheckableTag from 'antd/lib/tag/CheckableTag';
import './index.less';

export interface TabTableProps extends TableElementProps {
  tabListConfig: {
    showTabList?: boolean; // 是否显示tab
    tabList: { key: string; label: string; showColumnKeys: string[] }[]; // tab列表
    defaultColumnKeys?: string[]; // 默认显示的列
    defaultCheckedTabs?: string[]; // 默认选中的tab
  };
}

const TabsTable = forwardRef<TableElementRef, TabTableProps>(
  ({ columns, header, tabListConfig, ...rest }, ref) => {

    // 是否有默认选中的tab，没有的话默认选中全部
    const [checkedTabs, setCheckedTabs] = useState<string[]>(
      tabListConfig?.defaultCheckedTabs != undefined && tabListConfig?.defaultCheckedTabs.length > 0
        ? [...tabListConfig?.defaultCheckedTabs]
        : tabListConfig.tabList.map((item) => item.key),
    );

    const columnHeaderStyle = useMemo(
      () => ({
        color: '#1890ff',
        fontWeight: 'bold',
        border: '1px solid #e5e9f2',
        backgroundColor: '#f9fafc',
        borderRadius: 5,
        minWidth: 120,
      }),
      [],
    );

    const tableColumns = useMemo(() => {
      const { showTabList, tabList, defaultColumnKeys = [] } = tabListConfig;
      if (showTabList) {
        const defaultColumns = columns.filter((item: any) =>
          defaultColumnKeys?.includes(item.dataIndex),
        );
        const checkedColumns = tabList
          .filter((tab) => checkedTabs.includes(tab.key))
          .map((tab) => {
            const { showColumnKeys = [], key, label } = tab;
            return {
              title: label,
              dataIndex: key,
              onHeaderCell: () => ({
                style: columnHeaderStyle,
              }),
              children: showColumnKeys.map(
                (showColumnKey) =>
                  columns.find((column: any) => showColumnKey === column.dataIndex) ?? {
                    title: '',
                    dataIndex: '',
                    width: 200,
                  },
              ),
            };
          });
        return [...defaultColumns, ...checkedColumns];
      }

      return columns;
    }, [checkedTabs, tabListConfig, columns]);

    const headerRender = useMemo(() => {
      const { tabList } = tabListConfig;
      return (
        <div className="tab_table-tabs">
          <CheckableTag
            checked={checkedTabs.length === tabList.length}
            style={{ margin: '2px 5px 2px 0' }}
            onChange={() => {
              setCheckedTabs((prev) => {
                return prev.length === tabList.length ? [] : tabList.map(({ key }) => key);
              });
            }}
          >
            {'全部'}
          </CheckableTag>
          {tabList.map((item) => {
            const checked = checkedTabs.includes(item.key);
            return (
              <Tag.CheckableTag
                checked={checked}
                key={item.key}
                style={{ margin: '2px 5px 2px 0' }}
                onChange={() => {
                  setCheckedTabs((prev) => {
                    const isSelectAll = prev.length === tabList.length;
                    if (isSelectAll) {
                      return [item.key];
                    } else {
                      //选择的顺序必须和tabList的顺序一致
                      return tabList
                        .filter((tab) =>
                          tab.key === item.key ? !checked : checkedTabs.includes(tab.key),
                        )
                        .map((tab) => tab.key);
                    }
                  });
                }}
              >
                {item.label}
              </Tag.CheckableTag>
            );
          })}
        </div>
      );
    }, [checkedTabs, tabListConfig]);

    return (
      <TableElement isTabsTable columns={tableColumns} header={headerRender} ref={ref} {...rest} />
    );
  },
);

export default TabsTable;
